package array;

public class leetCode670_maximumSwap {

    public int maximumSwap(int num) {

        String s = String.valueOf(num);
        char[] chars = s.toCharArray();
        int maxIndex = s.length() - 1;
        int[] maxArr = new int[chars.length];
        for (int i = chars.length - 1; i >= 0; i--) {
            if(chars[i] > chars[maxIndex]){
                maxIndex = i;
            }
            maxArr[i] = maxIndex;
        }

        for (int i = 0; i < chars.length; i++) {
            if(chars[maxArr[i]] != chars[i]){
                char tmp = chars[i];
                chars[i] = chars[maxArr[i]];
                chars[maxArr[i]] = tmp;
                break;
            }
        }

        return Integer.parseInt(new String(chars));


    }
}
